package com.sinog.alarm.easyexcel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.sinog.alarm.AlarmApplication;
import com.sinog.alarm.service.impl.ZoningServiceImpl;
import com.sinog.alarm.util.Constants;
import com.sinog.alarm.util.GkObjectUtils;
import com.sinog.alarm.util.JsonUtil;
import com.sinog.alarm.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author wangxj
 * @desc excel监听器
 * @date 2022-11-01 14:13
 */
@Slf4j
public class ExcelListener extends AnalysisEventListener<ZoneInfo> {

    private String uuid;
    List<ZoneInfo> zoneInfos = new ArrayList<>(600);
    private StringRedisTemplate stringRedisTemplate;
    // 手动控制事务
    private ZoningServiceImpl zoningService;
    public ExcelListener(String uuid) {
        this.uuid = uuid;
    }

    /**
     * 解析excel后执行invode操作
     *
     * @param data    解析的zoneInfo数据 one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context analysis context
     */
    @Override
    public void invoke(ZoneInfo data, AnalysisContext context) {
        log.info("解析到一条数据:{ " + data + " }");
        try {
            boolean allFieldNull1 = GkObjectUtils.isAllFieldNull1(data);
            if (!allFieldNull1) {
                // 将excel中每行都记录再zoneInfos列表中,后续整理列表执行
                zoneInfos.add(data);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * doAfterAllAnalysed
     * @param context context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("excel解析完毕:{}", context);
        if(0 < zoneInfos.size()) {
            // 调用save方法开始执行
            saveData(context);
        }
        zoneInfos.clear();
    }

    /**
     * 调用解析入库方法
     * @param context context
     */
    private void saveData(AnalysisContext context) {
        SimpleDateFormat simformat = new SimpleDateFormat("yyyyMMdd");
        String dateformat = simformat.format(new Date());
        ArrayList<ZoneInfo> resultSheetInfos = new ArrayList<>();
        ApplicationContext applicationContext = AlarmApplication.applicationContext;
        if (!ObjectUtils.allNotNull(zoningService)) {
            zoningService =(ZoningServiceImpl) applicationContext.getBean("zoningServiceImpl");
        }
        if (!ObjectUtils.allNotNull(stringRedisTemplate)) {
            stringRedisTemplate = (StringRedisTemplate) applicationContext.getBean("stringRedisTemplate");
        }
        // 拆分不同的excel,执行不同的操作
        for (ZoneInfo zoneInfo : zoneInfos) {
            // zoneInfo类设计的原则满足了行政区划功能
            String optionName = zoneInfo.getOptionName();
            // 为每一行生成一个uuid,合并与修改每次都生成一个uuid,供退回功能使用
            long mergeUuid;
            if(StrUtil.containsEquals(optionName,Constants.ZHCN.XGDS,Constants.ZHCN.XGQX,Constants.ZHCN.XGJD,
                    Constants.ZHCN.QXXZQHHB,Constants.ZHCN.JDXZQHHB,Constants.ZHCN.QXXZQHQY,Constants.ZHCN.JDXZQHQY,Constants.ZHCN.QXXZQHSC,Constants.ZHCN.JDXZQHSC)) {
                mergeUuid = stringRedisTemplate.opsForHash().increment("mergeUuid", dateformat,1L);
                String uuid = dateformat+ mergeUuid;
                log.error("执行:{},生成uuid:{}",JsonUtil.toText(zoneInfo),uuid);
                if(Constants.ZHCN.XGDS.equals(optionName)) {
                    zoningService.toUpdateXgds(zoneInfo,uuid);
                } else if (Constants.ZHCN.XGQX.equals(optionName)) {
                    zoningService.toUpdateXgqx(zoneInfo,uuid);
                } else if(Constants.ZHCN.XGJD.equals(optionName)) {
                    zoningService.toUpdateXgjd(zoneInfo,uuid);
                } else if(Constants.ZHCN.QXXZQHHB.equals(optionName)) {
                    zoningService.toMergeQx(zoneInfo,uuid);
                } else if(Constants.ZHCN.JDXZQHHB.equals(optionName)) {
                    zoningService.toMergeJd(zoneInfo,uuid);
                    // 区县行政区划迁移
                } else if(Constants.ZHCN.QXXZQHQY.equals(optionName)) {
                    zoningService.toTransferQx(zoneInfo,uuid);
                    // 街道行政区划迁移
                } else if(Constants.ZHCN.JDXZQHQY.equals(optionName)) {
                    zoningService.toTransferJd(zoneInfo,uuid);
                    // 删除行政区划
                } else if(StrUtil.containsEquals(optionName,Constants.ZHCN.QXXZQHSC,Constants.ZHCN.JDXZQHSC)) {
                    zoningService.toDeleteXzqh(zoneInfo,uuid);
                }
                // 新增地市/区县/街道
            } else if(StrUtil.containsEquals(optionName,Constants.ZHCN.XZDS,Constants.ZHCN.XZQX,Constants.ZHCN.XZJD)) {
                zoningService.toSaveXzds(zoneInfo);
            }
            resultSheetInfos.add(zoneInfo);
        }
        // redis key:uuid+sheet页+sheet行数据,value:返回数据
        stringRedisTemplate.opsForHash().put("area_merge", uuid + ":" + context.getCurrentSheet().getSheetNo() + JsonUtil.toText(context.readRowHolder().getCurrentRowAnalysisResult()), JsonUtil.toText(resultSheetInfos));
    }
}
